package yxy.game.pm2.command.hero;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.Hero;
import yxy.game.pm2.bean.currency.Currencies;
import yxy.game.pm2.bean.currency.CurrencyType;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.HeroMessage;
import yxy.game.pm2.module.CurrencyHandle;
import yxy.game.pm2.module.hero.HeroHandle;

/** 武将装备 武将一键卸装 */
@MessageType(proto = Command.HeroEquipOffFast, classtype = HeroMessage.HeroEquipOffFastRequest.class)
public class CMD_HeroEquipOffFast extends Command<HeroMessage.HeroEquipOffFastRequest> {

	@Override
	public void execute(MessageSource messageSource, HeroMessage.HeroEquipOffFastRequest request) {
		String playerCode = messageSource.getTag();
		String code = request.getCode();

		HeroMessage.HeroEquipOffFastResponse.Builder response = HeroMessage.HeroEquipOffFastResponse.newBuilder();

		try {
			if (Hero.lockHero(playerCode)) {
				HeroHandle heroHandle = new HeroHandle();
				Hero hero = heroHandle.getHero(playerCode, code);
				if (hero == null) {
					send(messageSource, response, Result.ParamError);
					return;
				}

				Currencies back = new Currencies();
				// 卸下装备
				int[] equips = hero.getEquips();
				for (int i = 0; i < equips.length; i++) {
					if (equips[i] > 0) {
						back.add(Currency.create(CurrencyType.CT_装备, equips[i], 1));
					}
				}

				back.add(hero.trainAll());

				hero.setEquips(null);
				// 存档


				heroHandle.updateHero(playerCode, hero);

				HeroMessage.HeroInfo heroInfo = heroHandle.getHeroInfo(playerCode, hero);
				response.setInfo(heroInfo);
				response.addAllBack(new CurrencyHandle().packItems(back));
				send(messageSource, response, Result.Success);

				heroHandle.heroTipNotification(playerCode, hero);
			}
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		} finally {
			Hero.unlockHero(playerCode);
		}
	}

	private void send(MessageSource messageSource, HeroMessage.HeroEquipOffFastResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}